package com.dianban.utils;

import com.alibaba.fastjson.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wujh
 * @version 2020/7/9
 */
public class SmsUtil {

    private static String DEV_ID = "9aaea376f51b4a0b923afb7edb139301";         						//短信账号id

    private static String DEV_KEY = "f718245f3fc841829397e003ad74e791";         						//短信账号密钥

    private static String SEND_URL = "http://www.xinxinke.com/api/send";

    public static final String sendCodeContent ="您的验证码：${code}，2分钟内有效，请勿向他人泄露。若非本人操作，请忽略！";


    public static String sendSms(String phone, String templateCode, String smsSign, JSONObject smsParam) {
        String url = SEND_URL;
        String devId = DEV_ID;
        String devKey = DEV_KEY;
        String sign = MD5.parseMD5(devId + devKey + phone).toLowerCase();
        StringBuffer param = new StringBuffer();
        param.append("").append("dev_id").append("=").append(devId);
        param.append("&").append("sign").append("=").append(sign);
        param.append("&").append("sms_sign").append("=").append(smsSign);
        param.append("&").append("sms_template_code").append("=").append(templateCode);
        param.append("&").append("sms_param").append("=").append(smsParam);
        param.append("&").append("rec_num").append("=").append(phone);
        String result = HttpUtil.sendPost(url, param.toString());
        return result;
    }

    public static JSONObject getSmsParam(String content,Object ...obj){
        List<String> params= new ArrayList<String>();
        JSONObject smsParam = new JSONObject();
        //获取短信模板内容中的参数名
        Pattern pattern = Pattern.compile("\\{.*?\\}");
        Matcher matcher = pattern.matcher(content);
        while(matcher.find()){
            params.add(matcher.group().substring(1,matcher.group().length()-1));
        }
        for (int i = 0; i < params.size(); i++) {
            smsParam.put(params.get(i), obj[i]);
        }
        return smsParam;
    }
}
